#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<arpa/inet.h>

int main()
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        perror("Get fd fail\n");
        return -1;
    }
    
    struct sockaddr_in saddr;

    saddr.sin_family = AF_INET;     //协议
    saddr.sin_port = htons(7676);   //设定端口号，并进行大小端序的转换
    saddr.sin_addr.s_addr = INADDR_ANY; //自动读取主机网卡IP，绑定网卡IP
    int ret = bind(fd, (struct sockaddr*)&saddr, sizeof(saddr));
    if(ret == -1)
    {
        perror("bind error\n");
        return -1;
    }

    ret = listen(fd, 128);  //开始监听是否有客户端连接申请
    if(ret == -1)
    {
        perror("listen error\n");
        return -1;
    }

    /* 阻塞等待连接申请 */
    struct sockaddr_in csaddr;
    socklen_t socklen = sizeof(csaddr);
    int cfd = accept(fd, (struct sockaddr*)&csaddr, &socklen);
    if(cfd == -1)
    {
        perror("accept error\n");
        return -1;
    }

    char ip_buff[32];
    printf("客户端IP：%s，端口：%d\n",inet_ntop(AF_INET, &csaddr.sin_addr.s_addr, ip_buff, sizeof(ip_buff)), ntohs(csaddr.sin_port));

    while(1)
    {
        char buff[1024];
        int len = recv(cfd, buff, sizeof(buff), 0);
        if(len == 0)    //len返回0表示断开连接
        {   
            printf("客户端断开连接...\n");
            break;
        }
        else if(len > 0)     //len为正数表示接收到len个数据
        {
            printf("client say: %s\n", buff);
            send(cfd, buff, len, 0);
        }
        else
        {
            printf("recv error\n");
            break;
        }
    }
    
    close(fd);
    close(cfd);

    return 0;
}